package com.xhdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xhdp.dto.Result;
import com.xhdp.dto.UserDTO;
import com.xhdp.entity.Follow;
import com.xhdp.mapper.FollowMapper;
import com.xhdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhdp.service.IUserService;
import com.xhdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaohe
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IUserService userService;

    /**
     * 关注/取关用户
     * @param followUserId
     * @param isFollow
     * @return
     */
    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        //获取登录用户id
        Long userId = UserHolder.getUser().getId();
        String followKey = "follows:" + userId;
        //判断是关注还是取关
        if (isFollow) {
            //关注，新增数据
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            boolean isSuccess = save(follow);
            if (isSuccess) {
                //把关注用户的 id 放入 Redis 的 set 集合 SADD userId followUserId
                stringRedisTemplate.opsForSet().add(followKey, followUserId.toString());
            }
        } else {
            //取关，删除数据
            boolean isSuccess = remove(new QueryWrapper<Follow>()
                    .eq("user_id", userId).eq("follow_user_id", followUserId));
            if (isSuccess) {
                //把关注用户的 id 从 Redis 集合移除
                stringRedisTemplate.opsForSet().remove(followKey, followUserId.toString());
            }
        }
        return Result.ok();
    }

    /**
     * 是否关注用户
     * @param followUserId
     * @return
     */
    @Override
    public Result followOrNot(Long followUserId) {
        //获取登录用户id
        Long userId = UserHolder.getUser().getId();
        //查询是否关注用户
        Integer count = query().eq("user_id", userId).eq("follow_user_id", followUserId).count();
        //返回结果
        return Result.ok(count > 0);
    }

    @Override
    public Result commonFollow(Long userId) {
        //获取当前用户
        Long currentUserId = UserHolder.getUser().getId();
        //求交集
        String currentFollowKey = "follows:" + currentUserId;
        String followKey = "follows:" + userId;
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(currentFollowKey, followKey);
        if (intersect == null || intersect.isEmpty()) {
            //无交集，说明没有共同关注用户
            return Result.ok(Collections.emptyList());
        }
        //有交集，解析 id 集合
        List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
        //查询用户
        List<UserDTO> userDTOS = userService.listByIds(ids)
                .stream().
                map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());

        return Result.ok(userDTOS);
    }
}
